//
//  MSTool.m
//  MS
//
//  Created by He Yuan on 13-2-6.
//  Copyright (c) 2013年 He Yuan. All rights reserved.
//

#import "MSTool.h"

NSString * const CCRTErrorDomain = @"MSErrorDomain";

@implementation MSTool

//check email
+(BOOL)checkEmailValue:(NSString*)string
{
    if(![string isMatchedByRegex:@"\\b([a-zA-Z0-9%_.+\\-]+)@([a-zA-Z0-9.\\-]+?\\.[a-zA-Z]{2,6})\\b"])
    {
        return NO;
    }
    return YES;
}

+(UILabel *)createLable:(CGRect)rect
{
    UILabel *lbl = [[UILabel alloc]initWithFrame:rect];
    lbl.backgroundColor = [UIColor clearColor];
    lbl.font = FONT_NORMAL;
    lbl.textColor = [UIColor blackColor];
    return lbl;
}

+(UITextField *)createTextField:(CGRect)rect
{
    UITextField *txtField = [[UITextField alloc]initWithFrame:rect];
    txtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    txtField.borderStyle = UITextBorderStyleRoundedRect;
    txtField.clearButtonMode = UITextFieldViewModeWhileEditing;
    txtField.font = FONT_NORMAL;
    txtField.textColor = [UIColor blackColor];
    return txtField;
}

+(UIButton *)createButton:(CGRect)rect action:(SEL)sel delegate:(id)delegate
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setFrame:rect];
    [btn.titleLabel setFont:FONT_MIDDLE_BOLD];
    if ([delegate respondsToSelector:sel]) {
        [btn addTarget:delegate action:sel forControlEvents:UIControlEventTouchUpInside];
    }
    return btn;
}


+(void)showAlertTitle:(NSString*)title message:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:title message:msg delegate:nil cancelButtonTitle:HYLocalizedString(@"确定") otherButtonTitles:nil, nil];
    [alert show];
}


+(void)showAlertTitle:(NSString*)title message:(NSString *)msg delegate:(id)d
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:title message:msg delegate:nil cancelButtonTitle:HYLocalizedString(@"确定") otherButtonTitles:nil, nil];
    alert.delegate = d;
    [alert show];
}

+(void)showAlert:(NSString*)msg
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:msg message:nil delegate:nil cancelButtonTitle:HYLocalizedString(@"确定") otherButtonTitles:nil, nil];
    [alert show];
}

+(void)showAlert:(NSString*)msg delegate:(id)d
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:msg message:nil delegate:nil cancelButtonTitle:HYLocalizedString(@"确定") otherButtonTitles:nil, nil];
    alert.delegate = d;
    [alert show];
}


+(void)showHUD:(NSString*)msg done:(BOOL)done inView:(UIView *)v
{
    [[HYProgressHUD sharedProgressHUD] setText:msg];
    [[HYProgressHUD sharedProgressHUD]showInView:v];
    [[HYProgressHUD sharedProgressHUD]done:done];
}

+(void)showHUD:(NSString*)msg done:(BOOL)done
{
    [MSTool showHUD:msg done:done inView:[[UIApplication sharedApplication] keyWindow]];
}

+(void)refreshHUDText:(NSString*)msg
{
    [[HYProgressHUD sharedProgressHUD]setText:msg];
}

+(void)refreshHUD:(NSString*)msg done:(BOOL)done
{
    [[HYProgressHUD sharedProgressHUD]setText:msg];
    [[HYProgressHUD sharedProgressHUD]done:done];
}

+(void)showHUD:(NSString *)msg
{
    [MSTool showHUD:msg inView:[[UIApplication sharedApplication]keyWindow]];
}

+(void)showHUD:(NSString *)msg inView:(UIView *)v
{
    [[HYProgressHUD sharedProgressHUD] setText:msg];
    [[HYProgressHUD sharedProgressHUD]showInView:v];
}

+(void)hideHUD
{
    [[HYProgressHUD sharedProgressHUD]hide];
}

+(void)hideHUD:(BOOL)done
{
    [[HYProgressHUD sharedProgressHUD]done:done];
}


//获取随机数
+(long)getRandomNumber:(long)from to:(long)to
{
    srandom(time(NULL)); //将随机数种子重置,
    long randomnum = (long)(from + (arc4random()%(to-from + 1)));
    return randomnum;
}

+(long)getRandomNumber
{
    return [MSTool getRandomNumber:100000 to:999999];
}

//去掉空格
+(NSString *)trimmingWhiteSpaceCharacter:(NSString *)str
{
    if (str == nil || [str length]<1)return nil;
    NSString *newstr = [str stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    newstr = [newstr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return newstr;
}

+(NSString *)TrimJsonChar:(NSString *)jsonstr
{
	NSString *responseString;
	
	responseString = [jsonstr
					  stringByReplacingOccurrencesOfString:@"\15" withString:@""];
	responseString = [responseString
					  stringByReplacingOccurrencesOfString:@"\n" withString:@""];
	responseString = [responseString
					  stringByReplacingOccurrencesOfString:@"\r" withString:@""];
	responseString = [responseString
					  stringByTrimmingCharactersInSet:
					  [NSCharacterSet whitespaceAndNewlineCharacterSet]];
	
	return responseString;
}

+ (NSString *)documentsDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
    return documentsDirectory;
}

+ (NSString *)tmpDirectory
{
    return [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"];
}

+ (NSString *)imagePathWithSubDir:(NSString *)subDir
{
    NSString *dirPath = [MSTool documentsDirectory];
    return [dirPath stringByAppendingPathComponent:
            [NSString stringWithFormat:@"/Images/%@",subDir]];
}

+(void)createFileDirIfNotExists:(NSString *)fileDir
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    if (![fileManager fileExistsAtPath:fileDir isDirectory:nil]) {
        BOOL createDirSucceed = [fileManager createDirectoryAtPath:fileDir
                                       withIntermediateDirectories:YES
                                                        attributes:nil
                                                             error:&error];
        if (!createDirSucceed)
        {
            HYLog(@"Create file directory:%@ failed.", fileDir);
        }
    }
}

+ (NSString *)cacheRandomImages
{
    return [self imagePathWithSubDir:@"imagecache"];
}

+(NSString *)convertStringEnCodeToUTF8:(NSString *)string
{
    NSString *symobltxt = @"";
    
    if ([string canBeConvertedToEncoding:NSShiftJISStringEncoding])
    {
        symobltxt  = [NSString stringWithCString:[string cStringUsingEncoding:NSShiftJISStringEncoding] encoding:NSUTF8StringEncoding];
        if (symobltxt == nil || [symobltxt isEqual:[NSNull null]] || [symobltxt length]<1)
        {
            symobltxt = string;
        }
    }
    else
    {
        symobltxt = string;
    }
    return symobltxt;
}

+(NSUInteger)getByteForStringLenth:(NSString *)string
{
    NSData *_data = [string dataUsingEncoding:NSUTF8StringEncoding];
    return [_data length];
}

+(NSError *)createError:(NSInteger)errorcode localDescription:(NSString *)des
{
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    [userInfo setValue:des forKey:NSLocalizedDescriptionKey];
    return  [NSError errorWithDomain:CCRTErrorDomain code:errorcode userInfo:userInfo];
}

+(void)showError:(NSError *)error
{
    if (error != nil)
        [MSTool showHUD:error.localizedDescription done:NO];
    else
        [MSTool hideHUD];
}

//将图片处理成圆形
+(UIImage*) circleImage:(UIImage*) image withParam:(CGFloat) inset {
    UIGraphicsBeginImageContext(image.size);
	CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context,10);
    CGContextSetStrokeColorWithColor(context, [UIColor colorWithWhite:0.813 alpha:1.000].CGColor);
	CGRect rect = CGRectMake(inset, inset, image.size.width - inset * 2.0f, image.size.height - inset * 2.0f);
	CGContextAddEllipseInRect(context, rect);
	CGContextClip(context);
	
	[image drawInRect:rect];
    CGContextAddEllipseInRect(context, rect);
	CGContextStrokePath(context);
    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newimg;
}

+(NSString *)convertObjectToJson:(NSDictionary *)obj
{
    if ([NSJSONSerialization isValidJSONObject:obj])
    {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:0 error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return json;
    }
    return nil;
}

+(NSDictionary *)convertJsonToDictionary:(NSString *)json
{
    if (!json) {
        return nil;
    }
    NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    if (dict == nil)NSLog(@"json parse failed \r\n");
    return dict;;
}

@end